/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.lgiavedoni.frank.view;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.lgiavedoni.android.franq.core.communication.CommunicationType;
import org.lgiavedoni.android.franq.core.message.Message;
import org.lgiavedoni.android.franq.core.message.MessageIn;
import org.lgiavedoni.android.franq.core.message.MessageOut;
import org.lgiavedoni.android.franq.service.communication.CommunicationService;
import org.lgiavedoni.android.franq.service.phone.ContextService;
import org.lgiavedoni.frank.view.communication.CommunicationPhone;
import org.lgiavedoni.frank.view.service.FrankService;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * Activity that lets users browse through Wiktionary content. This is just the
 * user interface, and all API communication and parsing is handled in
 * {@link ExtendedWikiHelper}.
 */
public class LookupActivity extends Activity implements AnimationListener{
    private static final String TAG = "LookupActivity";
    
    private View mTitleBar;
    private TextView mTitle;
    private ProgressBar mProgress;
    private TextView mainTextView;
    private static ScrollView scrollView;
    private static LinearLayout linearLayout;
    private static List<Message> msg = new ArrayList<Message>();
    private EditText editText;
    private static Thread thread;
    
    private final Handler mHandler = new Handler();
    final Runnable mUpdateResults = new Runnable() {
        public void run() {
            updateUI();
        }
    };

    
    
    private Button send;
    
    private Animation mSlideIn;
    private Animation mSlideOut;

    /**
     * History stack of previous words browsed in this session. This is
     * referenced when the user taps the "back" key, to possibly intercept and
     * show the last-visited entry, instead of closing the activity.
     */
   

    
    public static LookupActivity mThis;
    
    
    
    @Override
	protected void onStart() {
    	//CommunicationService.inst.sendDefaultTextMessage("onStart");
    	getApplication().getApplicationContext().startService(new Intent(getApplication().getApplicationContext(), FrankService.class));
		super.onStart();
	}



	@Override
	protected void onRestart() {
		//CommunicationService.inst.sendDefaultTextMessage("onRestart");
		getApplication().getApplicationContext().startService(new Intent(getApplication().getApplicationContext(), FrankService.class));
		super.onRestart();
	}



	@Override
	protected void onResume() {
		//CommunicationService.inst.sendDefaultTextMessage("onResume");
		getApplication().getApplicationContext().startService(new Intent(getApplication().getApplicationContext(), FrankService.class));
		super.onResume();
	}



	@Override
	protected void onStop() {
		//CommunicationService.inst.sendDefaultTextMessage("onStop");
		super.onStop();
	}



	@Override
	protected void onDestroy() {
		CommunicationService.inst.sendDefaultTextMessage("onDestroy");
		super.onDestroy();
	}



	/**
     * {@inheritDoc}
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.lookup);
        mThis = this;
        
        // Load animations used to show/hide progress bar
        mSlideIn = AnimationUtils.loadAnimation(this, R.anim.slide_in);
        mSlideOut = AnimationUtils.loadAnimation(this, R.anim.slide_out);
        
        // Listen for the "in" animation so we make the progress bar visible
        // only after the sliding has finished.
        mSlideIn.setAnimationListener(this);
        
        mTitleBar = findViewById(R.id.title_bar);
        mTitle = (TextView) findViewById(R.id.title);
        mProgress = (ProgressBar) findViewById(R.id.progress);
        scrollView = (ScrollView) findViewById(R.id.scroller);
        linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        scrollView.addView(linearLayout);
        
        editText =  (EditText) findViewById(R.id.edtInput);
        send = (Button) findViewById(R.id.btn_submit);
        send.setOnClickListener(new SubmitOnClickListener());

        // Make the view transparent to show background
        //mainTextView.setBackgroundColor(0);
        mTitle.setText("Frank Chat:");
        

       
        // Handle incoming intents as possible searches or links
        onNewIntent(getIntent());
    }
    
    private class SubmitOnClickListener implements OnClickListener{  
            
    	 public void onClick(View v)  
             {      
    		 	   String text= editText.getText().toString();
    		 	   CommunicationService.inst.reciveMessage(MessageIn.create(CommunicationPhone.inst,text));
    		 	   addText(MessageIn.create(CommunicationPhone.inst, text));
                   InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
                   imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                   editText.setText("");
          
             }  
               
         }; 
         
         public  synchronized void addText(Message message){
        	 if(message==null || message.getText().trim().length()==0)
        		 return;
        	 
        	 //synchronized(msg){
        	 msg.add(message);
        		// msg.notifyAll();
        	 //}
        	 
        	 new Thread() {
        	            @Override
        				public void run() {
        	            	mHandler.post(mUpdateResults);
        	            }
        	        }.start();
        	       		 
        	 
         }
         
        
    
    /**
     * Intercept the back-key to try walking backwards along our word history
     * stack. If we don't have any remaining history, the key behaves normally
     * and closes this activity.
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
   
        
        // Otherwise fall through to parent
        return super.onKeyDown(keyCode, event);
    }

    private void startNavigating(String word) {
              
        // Start lookup for new word in background
        new LookupTask().execute(word);
    }
    
    /**
     * {@inheritDoc}
     */ 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.lookup, menu);
        return true;
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.lookup_about: {
                showAbout();
                return true;
            }
        }
        return false;
    }

    /**
     * Show an about dialog that cites data sources.
     */
    protected void showAbout() {
        // Inflate the about message contents
        View messageView = getLayoutInflater().inflate(R.layout.about, null, false);
        
        // When linking text, force to always use default color. This works
        // around a pressed color state bug.
        TextView textView = (TextView) messageView.findViewById(R.id.about_credits);
        int defaultColor = textView.getTextColors().getDefaultColor();
        textView.setTextColor(defaultColor);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.app_icon);
        builder.setTitle(R.string.app_name);
        builder.setView(messageView);
        builder.create();
        builder.show();
    }

    

    /**
     * Set the title for the current entry.
     */
    protected void setEntryTitle(String entryText) {
       
        mTitle.setText(entryText);
    }

    /**
     * Set the content for the current entry. This will update our
     * {@link WebView} to show the requested content.
     */
    protected void setEntryContent(String entryContent) {
       
    }

    /**
     * Background task to handle Wiktionary lookups. This correctly shows and
     * hides the loading animation from the GUI thread before starting a
     * background query to the Wiktionary API. When finished, it transitions
     * back to the GUI thread where it updates with the newly-found entry.
     */
    private class LookupTask extends AsyncTask<String, String, String> {
        /**
         * Before jumping into background thread, start sliding in the
         * {@link ProgressBar}. We'll only show it once the animation finishes.
         */
        @Override
        protected void onPreExecute() {
            mTitleBar.startAnimation(mSlideIn);
        }

        /**
         * Perform the background query using {@link ExtendedWikiHelper}, which
         * may return an error message as the result.
         */
        @Override
        protected String doInBackground(String... args) {
            
            
            return "test";
        }
        
        /**
         * Our progress update pushes a title bar update.
         */
        @Override
        protected void onProgressUpdate(String... args) {
            String searchWord = args[0];
            setEntryTitle(searchWord);
        }

        /**
         * When finished, push the newly-found entry content into our
         * {@link WebView} and hide the {@link ProgressBar}.
         */
        @Override
        protected void onPostExecute(String parsedText) {
            mTitleBar.startAnimation(mSlideOut);
            mProgress.setVisibility(View.INVISIBLE);
            
            setEntryContent(parsedText);
        }
    }

    /**
     * Make the {@link ProgressBar} visible when our in-animation finishes.
     */
    public void onAnimationEnd(Animation animation) {
        mProgress.setVisibility(View.VISIBLE);
    }

    public void onAnimationRepeat(Animation animation) {
        // Not interested if the animation repeats
    }

    public void onAnimationStart(Animation animation) {
        // Not interested when the animation starts
    }

    
    private void updateUI(){
    	//synchronized (msg) {
    	//	List<Message> l2 = msg.toArray();	
    		linearLayout.removeAllViews();
    		Iterator<Message> i= msg.iterator();
    		while(i.hasNext()){
        		//msg.remove(s);
    			Message s = i.next();
        		
        		TextView tv =new TextView(ContextService.inst.getApplicationContext());
        		if(s instanceof MessageOut){
        			tv.setText(((MessageOut) s).getText(CommunicationType.phone));
        		}else{
        			tv.setText(s.getText());
        			tv.setGravity(Gravity.RIGHT);
        		}
    			ImageView iv = new ImageView(ContextService.inst.getApplicationContext());
    			iv.setImageResource(R.drawable.star_logo);
    			//linearLayout.addView(iv);
    			linearLayout.addView(tv);
        	}
		//}
    	
    	
    	        	
    }
		
}
